package org.footballmanager.pandafootball.system.controller.hy;

import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.controller.BaseController;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.form.impl.FootGpSearchForm;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.DecimalFormat;
import java.util.Date;

@Controller
@SessionAttributes("footGpSearchForm")
@RequestMapping("/hy/footGp")
public class HyGpController extends BaseController {
	/* 实体名称 */
	private static final String ENTITYNAME = "footGp";
	private static final String ADDPAGE = String.format(Constants.ADDPAGE, Constants.HY, ENTITYNAME);
	private static final String LISTPAGE = String.format(Constants.LISTPAGE, Constants.HY, ENTITYNAME);
	private static final String REDIRECT = String.format(Constants.REDIRECT, Constants.HY, ENTITYNAME);

	@Autowired
	private FootGpService footGpService;
	
	@Autowired
	private FootPersonService footPersonService;
	
	@Autowired
	private FootUserPersonService footUserPersonService;
	
	@Autowired
	private FootTeamService footTeamService;
	
	@Autowired
	private FootZnxService footZnxService;
	
	@Autowired
	private FootZjService footZjService;
	
	@Autowired
	private FootTaxService footTaxService;

    /**
     * 初始化
     * @param map 参数
     * @param footGpSearchForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, HttpServletRequest request, @ModelAttribute FootGpSearchForm footGpSearchForm){
        footGpService.clear(request);
        FootUser user = (FootUser)request.getSession().getAttribute(Constants.USER);
        map.addAttribute("qyList", footUserPersonService.findCanGpPerson(user.getId()));
        FootGpSearchForm newFootGpSearchForm = new FootGpSearchForm();
        if(footGpSearchForm != null){
            newFootGpSearchForm = footGpSearchForm;
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newFootGpSearchForm);
    }

	//挂牌中心
	@RequestMapping(value="/search")
	public String search(Model map, @ModelAttribute FootGpSearchForm footGpSearchForm) {
        footGpSearchForm.setCj(false);
        footGpService.search(ENTITYNAME, map, footGpSearchForm);
		return LISTPAGE;
	}

	//我的挂牌球员
	@RequestMapping(value="/mySearch", method= RequestMethod.GET)
	public String mySearch(Model map, HttpServletRequest request, @ModelAttribute FootGpSearchForm footGpSearchForm) {
		FootUser user = (FootUser)request.getSession().getAttribute(Constants.USER);
        footGpSearchForm.setCj(false);
        footGpSearchForm.setSellUserId(user.getId());
        footGpService.search(ENTITYNAME, map, footGpSearchForm);
		return "hy/footGp/MyList";
	}

	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public String delete(@RequestParam Long id, HttpServletRequest request) {
		footGpService.delete(id, request);
		return "redirect:/hy/footGp/mysearch";
	}

	@RequestMapping(value = "/deleteall", method = RequestMethod.POST)
	public String deleteall(HttpServletRequest request, @ModelAttribute FootGpSearchForm footGpSearchForm) {
        footGpService.deleteAll(footGpSearchForm, request);
		return "redirect:/hy/footGp/mysearch";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String openAddPage(Model map, HttpServletRequest request) {
		FootUser user = (FootUser)request.getSession().getAttribute(Constants.USER);
		FootGp gp = new FootGp();
		gp.setSellUserId(user.getId());
		gp.setGpsj(new Date());
		map.addAttribute(ENTITYNAME, gp);
		return ADDPAGE;
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String save(@Valid @ModelAttribute FootGp footGp, BindingResult bindingResult,
			HttpServletRequest request, SessionStatus s) {
		if (!bindingResult.hasErrors()) {
			FootUserPerson fup = footUserPersonService.get(footGp.getFupId());
			fup.setGpzt(1);
			footUserPersonService.updateNotNull(fup, request);
			footGp.setQyId(fup.getQyId());
			FootPerson fp = footPersonService.get(fup.getQyId());
			if(footGp.getYkj() < Double.valueOf(fp.getQysj()) * 0.8 || footGp.getYkj() > Double.valueOf(fp.getQysj()) * 2){
                bindingResult.rejectValue("ykj", Constants.MISFORMAT, "一口价不能小于球员身价的80%且不能大于球员身价的200%");
				return ADDPAGE;
			}
			footGp.setCj(false);
			footGp.setQyName(fp.getName());
			footGp.setYw(fp.getYw());
			footGpService .save(footGp, request);
			s.setComplete();
			return REDIRECT;
		} else 
			return ADDPAGE;
	}

	@RequestMapping(value = "/isMyGp", method = RequestMethod.POST)
	@ResponseBody
	public String isMyGp(HttpServletRequest request, @RequestParam String gpid) {
		FootUser user = (FootUser)request.getSession().getAttribute(Constants.USER);
		FootTeam ft = footTeamService.getTeamByUserid(user.getId());
		FootGp fg = footGpService.get(gpid);
		return processMyGp(user, ft, fg);
	}

	private String processMyGp(FootUser user, FootTeam ft, FootGp fg){
		if(!user.getJoins() || !StringUtils.isEmpty(ft.getQdId())){
			return "对不起，系统没有找到您的球队！";
		}
		if(fg == null) {
			return "对不起，没有找到数据！";
		}
		if(fg.getSellUserId().equals(user.getId())){
			return "对不起，此球员是您挂牌出售的，请更换！";
		}
		//如果买不起即 一口价大于你的总资金
		if((fg.getYkj() * (1d + footTaxService.getDealTax())) > ft.getQdZzj()){
			return "对不起，您的球队资金不够购买该球员！";
		}
		return Constants.OK;
	}

	@RequestMapping(value = "/buy", method = RequestMethod.GET)
	public String buy(HttpServletRequest request, @RequestParam Long id) {
		FootUser user = (FootUser)request.getSession().getAttribute(Constants.USER);
		FootTeam ft = footTeamService.getTeamByUserid(user.getId());
		FootGp fg = footGpService.get(id);
		if(fg != null){
			fg.setCj(true);
			fg.setBuyUserId(user.getId());
			footGpService.updateNotNull(fg, request);
			if(fg.getFupId() != null){
				footUserPersonService.delete(fg.getFupId(), request);
			}
			FootPerson fp = footPersonService.get(fg.getQyId());
			
			footUserPersonService.saveUserPerson(user.getId(), fp, request);
			double result = fg.getYkj() * footTaxService.getDealTax();
			ft.setQdZzj(ft.getQdZzj() - fg.getYkj());
			footTeamService.updateNotNull(ft, request);
			FootTeam ft2 = footTeamService.getTeamByUserid(fg.getSellUserId());
			ft2.setQdZzj(ft2.getQdZzj() + result);
			footTeamService.updateNotNull(ft2, request);
			footZnxService.sendZnx(user.getId(), fg.getSellUserId(), user.getNike() +
					"已经成功从挂牌中心抢走了玩家" + fg.getSellUserName() + "的球员" + fp.getYw() + "(" + fp.getName() + ")",
					footTeamService.getLogoByUserid(user.getId()), null, request);
			footZjService.sendZj(user.getId(), fg.getYkj(), false,
					"因购买玩家" + fg.getSellUserName() + "的球员" + fp.getYw() + "(" + fp.getName() + ")花费€" +
					new DecimalFormat(",###").format(fg.getYkj()) + "(含税),当前球队的总资金为:€" + 
					new DecimalFormat(",###").format(ft.getQdZzj()), request);
			footZjService.sendZj(fg.getSellUserId(), result, true,
					"因球员您的球员" + fp.getYw() + "(" + fp.getName() + ")被抢购,获得€" + 
					new DecimalFormat(",###").format(result) + ",当前球队的总资金为:€" + 
					new DecimalFormat(",###").format(ft2.getQdZzj()), request);
		}
		return REDIRECT;
	}
	
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	public String openViewPage(Model map, @PathVariable String qpid,
                @ModelAttribute FootGpSearchForm footGpSearchForm) {
		FootGp gp = footGpService.get(qpid);
		map.addAttribute(ENTITYNAME, gp);
        map.addAttribute("footPerson", footPersonService.get(gp.getQyId()));
		return "hy/footGp/QyView";
	}	
}
